package com.finger.crowd.filter;

import com.finger.crowd.constant.AccessPassResource;
import com.finger.crowd.constant.CrowdConstant;
import com.finger.crowd.util.CrowdUtils;
import com.google.common.base.Objects;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CrowdAccessFilter extends ZuulFilter {


    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {

        // 获取当前的context
        RequestContext currentContext = RequestContext.getCurrentContext();

        // 获取当前的请求对象
        HttpServletRequest request = currentContext.getRequest();

        // 获取当前请求对象的servlet名
        String servletPath = request.getServletPath();

        // 判断当前servletPath是否为放行路径
        boolean contains = AccessPassResource.PASS_RES_SET.contains(servletPath);

        if (contains) {
            return false;
        }
        boolean judgeCurrentServletPathWetherStaticResource = AccessPassResource.judgeCurrentServletPathWetherStaticResource(servletPath);

        return !judgeCurrentServletPathWetherStaticResource;
    }

    public Object run() throws ZuulException {

        // 获取当前请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();

        // 获取session对象
        HttpSession session = request.getSession();

        // 从session中获取登录对象
        Object attribute = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        // 如果为空
        if (attribute == null) {

            session.setAttribute("message", CrowdConstant.MESSAGE_ACCESS_FORBIDDEN);

            HttpServletResponse response = currentContext.getResponse();

            try {
                // 重定向到登录页面
                response.sendRedirect("/auth/member/to/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
